#include "functions.h"
#include "definitions.h"

#include <QTextCodec>
#include <QtNetwork>



FeedType Functions::qstrToFeedType(const QString &string) {
    if (string == "RSS") return FEED_RSS;
    if (string == "ATOM") return FEED_ATOM;
    return FEED_UNKNOWN;
}

QString Functions::feedTypeToQstring(const FeedType &type) {
    switch (type) {
        case FEED_RSS:
            return "RSS";
        case FEED_ATOM:
            return "ATOM";
        default:
            return "UNKNOWN";
    }
}

FeedType Functions::intToFeedType(int value) {
    switch (value) {
        case FEED_RSS:
            return FEED_RSS;
        case FEED_ATOM:
            return FEED_ATOM;
        default:
            return FEED_UNKNOWN;
    }
}

bool Functions::isValid(QList<QString> list) {
    try {
        foreach (QString item, list)
            if (item.size() < VALID_LIMIT) {
                return false;
            }
    }
    catch (std::exception &e) {
        return false;
    }

    return true;
}

bool Functions::qstrToBool(const QString &value) {
    if (value == "true" || value == "True") {
        return true;
    }
    else {
        return false;
    }
}

QNetworkReply::NetworkError Functions::downloadFileToQString(const QString &url, QByteArray *output, int timeout) {
    // a wacky way how to make asynchronous network calls
    // synchronous. The dedicated event loop is here to
    // ensure QtNetwork signals and slots behave like
    // synchronous curl-like call.
    QNetworkAccessManager manager;
    QEventLoop loop;
    QTimer timer;
    QNetworkRequest request;

    request.setUrl(url);
    request.setRawHeader("User-Agent", "RSSGuard");

    timer.setSingleShot(true);

    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    QNetworkReply *reply = manager.get(request);

    // TODO/FIXME: do we need it here?
    reply->ignoreSslErrors();

    timer.start(timeout);
    loop.exec();

    if (timer.isActive()){
        // download complete
        timer.stop();
    } else {
        return QNetworkReply::TimeoutError;
    }

    *output = reply->readAll();

    QNetworkReply::NetworkError ret = reply->error();
    if (ret != QNetworkReply::NoError)
        qWarning() << tr("%1Feed %2 fetched with error. %3").arg(APP_ID, url, reply->errorString());
    else
        qDebug() << tr("%1Feed %2 fetched with code %3, timeout %4 miliseconds.").arg(APP_ID, url, QString::number(reply->error()), QString::number(timeout));

    reply->deleteLater();

    return ret;
}
